/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author prateekpatil
 */
package loganalysis;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.io.*;
import java.util.Date.*;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.util.*;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.experimental.chart.plot.CombinedXYPlot;
import org.jfree.ui.ApplicationFrame;


/**
* A demonstration application showing a {@link CombinedXYPlot} with
* two subplots.
*/
public class Graph extends ApplicationFrame
{

/**
 * Constructs a new demonstration application.
 *
 * @param title  the frame title.
 */

    private static double averageExecTime;
    private static double avgMemory;
    private static TimeSeriesCollection collection1 = new TimeSeriesCollection();
    private static TimeSeriesCollection collection2 = new TimeSeriesCollection();
    JButton button = new JButton("STOP");
    private ArrayList<ArrayList<String>> intermediateData ;

    public JButton getButton() {
            return button;
    }

    public void setButton(JButton button) {
            this.button = button;
    }

    JPanel panel;

    public JPanel getPanel() {
            return panel;
    }

    public void setPanel(JPanel panel) {
            this.panel = panel;
    }

    public double getAvgCPU() {
            return averageExecTime;
    }

    public void setAvgCPU(double avgCPU) {
            this.averageExecTime = avgCPU;
    }

    public double getAvgMemory() {
            return avgMemory;
    }

    public void setAvgMemory(double avgMemory) {
            this.avgMemory = avgMemory;
    }



public Graph(String title) {
    super(title);
    JPanel panel = createDemoPanel();
    panel.setPreferredSize(new java.awt.Dimension(1500, 1500));
    panel.setLayout(null);
    panel.add(BorderLayout.SOUTH,button);
    setContentPane(panel);
    Insets insets = panel.getInsets();
    Dimension size = button.getPreferredSize();
    button.setBounds(1200+ insets.left, 10 + insets.top,
    size.width, size.height);

}



/**
 * Creates an overlaid chart.
 *
 * @return The chart.
 */
private static JFreeChart createCombinedChart() {

    // create plot ...
    IntervalXYDataset data1 = createDataset1();


   
    XYItemRenderer renderer1 = new XYLineAndShapeRenderer(true, false);
    renderer1.setBaseToolTipGenerator(new StandardXYToolTipGenerator(
            StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"), new DecimalFormat("0.00")));
    renderer1.setSeriesStroke(0, new BasicStroke(2.0f,
            BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer1.setSeriesPaint(0, Color.blue);


    DateAxis domainAxis = new DateAxis("Time");
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.04);
    ValueAxis rangeAxis = new NumberAxis("Usage Percentage");
    XYPlot plot1 = new XYPlot(data1, null, rangeAxis, renderer1);
    plot1.setBackgroundPaint(Color.lightGray);
    plot1.setDomainGridlinePaint(Color.white);
    plot1.setRangeGridlinePaint(Color.white);


    // add a second dataset and renderer...
    IntervalXYDataset data2 = createDataset2();
    XYItemRenderer renderer2 = new XYLineAndShapeRenderer(true, false);
    renderer2.setBaseToolTipGenerator(new StandardXYToolTipGenerator(
            StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"), new DecimalFormat("0.00")));
    renderer2.setSeriesStroke(0, new BasicStroke(2.0f,
            BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    renderer2.setSeriesPaint(0, Color.red);





    //ValueAxis
    rangeAxis = new NumberAxis("Usage Percentage");
    XYPlot plot2 = new XYPlot(data2, null, rangeAxis, renderer2);
    plot2.setBackgroundPaint(Color.lightGray);
    plot2.setDomainGridlinePaint(Color.white);
    plot2.setRangeGridlinePaint(Color.white);




    CombinedDomainXYPlot cplot = new CombinedDomainXYPlot(domainAxis);
    cplot.add(plot1, 3);
    cplot.add(plot2, 2);
    cplot.setGap(8.0);
    cplot.setDomainGridlinePaint(Color.white);
    cplot.setDomainGridlinesVisible(true);

    // return a new chart containing the overlaid plot...
    JFreeChart chart = new JFreeChart("Average CPU and Memory Utilization ",
            JFreeChart.DEFAULT_TITLE_FONT, cplot, false);
    chart.setBackgroundPaint(Color.white);
    LegendTitle legend = new LegendTitle(cplot);
    chart.addSubtitle(legend);
    return chart;
}

/**
 * Creates a sample dataset.  You wouldn't normally hard-code the
 * population of a dataset in this way (it would be better to read the
 * values from a file or a database query), but for a self-contained demo
 * this is the least complicated solution.
 *
 * @return The dataset.
 */
private static IntervalXYDataset createDataset1() {

    // create dataset 1...
    TimeSeries series1 = new TimeSeries("CPU", Millisecond.class);

    series1.add(new Millisecond(), averageExecTime);
    collection1.addSeries(series1);
    return collection1;

}

/**
 * Creates a sample dataset.  You wouldn't normally hard-code the
 * population of a dataset in this way (it would be better to read the
 * values from a file or a database query), but for a self-contained demo
 * this is the least complicated solution.
 *
 * @return A sample dataset.
 */
private static IntervalXYDataset createDataset2() {
    //TimeSeriesCollection dataset = new TimeSeriesCollection();

    TimeSeries series2 = new TimeSeries("Memory", Millisecond.class);
    series2.add(new Millisecond(),avgMemory);
    collection2.addSeries(series2);
    return collection2;

}

/**
 * Creates a panel for the demo (used by SuperDemo.java).
 *
 * @return A panel.
 */
public static JPanel createDemoPanel() {
    JFreeChart chart = createCombinedChart();
    return new ChartPanel(chart);
}

/**
 * Starting point for the demonstration application.
 *
 * @param args  ignored.
 */
public void updateGraph()
{
    for (int i =0; i<intermediateData.size();i++)
    {
       
        collection1.getSeries(0).add(new Millisecond(new Date(Long.parseLong(intermediateData.get(i).get(0)))),Double.parseDouble(intermediateData.get(i).get(1)));
       collection2.getSeries(0).add(new Millisecond(new Date(Long.parseLong(intermediateData.get(i).get(0)))),Double.parseDouble(intermediateData.get(i).get(7)));
       // collection1.getSeries(0).add(null, avgMemory);
}
}
public static void main (String [] args) throws InterruptedException{
    Graph obj = new Graph("Graph1");
    obj.pack();
    obj.setVisible(true);
    
    obj.ScanData("graph.txt");
    obj.updateGraph();
    obj.repaint();
    Thread.sleep(100000);
    obj.dispose();
    
}


 public void ScanData(String filePath)
       {
            String fullFilePath = filePath;
            String line ="";
            BufferedReader loadLogFile;
            //2D Array
         intermediateData = new ArrayList<ArrayList<String>>();
             //Create file object and read it 
            try {
            loadLogFile= new BufferedReader(new FileReader (fullFilePath));
                
            
        //Initialize Row and column counter
         int row = 0;
         int col = 0;
         //Nested Loops to read file 
         
         while( (line = loadLogFile.readLine())!=null)
         {
             Scanner scanLine = new Scanner(line);
             intermediateData.add(new ArrayList<String>());
             while(scanLine.hasNext())
             {
                 intermediateData.get(row).add(scanLine.next());
                 col++;
             }
             row++;
         }
         }
         catch(FileNotFoundException e)
         {
             System.err.println("Error in reading logs: "+e);
         }
      catch(IOException e)
                {
                    System.err.println("Error in finding log file: "+e);
                }
        // Tesing region 
        Iterator list = intermediateData.iterator();
        while(list.hasNext())
        {
            System.out.println(list.next());
        } 
       } 


}
